package com.wlcb.jpower.chat.task;

import com.wlcb.jpower.chat.service.customer.ChatService;
import com.wlcb.jpower.chat.service.customer.CustomerMsgService;
import com.wlcb.jpower.chat.service.customer.CustomerSettingService;
import com.wlcb.jpower.constant.RedisEunm;
import com.wlcb.jpower.im.cache.SessionCache;
import com.wlcb.jpower.im.model.DataPacket;
import com.wlcb.jpower.module.common.redis.RedisUtil;
import com.wlcb.jpower.utils.RedisHelpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: fei
 * @desc: 自动接入定时任务
 */
@Component
public class AutoAccessTask {

    @Autowired
    private ChatService chatService;
    @Autowired
    private CustomerSettingService settingService;
    private static final String LOCK_KEY = "autoConnectUser";

    // @Scheduled(fixedRate = 1000 * 60)
    public void autoConnectUser() {
        RedisHelpUtils.RedisLock redisLock = RedisHelpUtils.getRedisLock();

        boolean tryLock = redisLock.tryLock(LOCK_KEY);
        if (tryLock) {
            try {
                List<String> autoAccess = settingService.findAutoAccess();
                List<DataPacket.Wait> waitUsers = chatService.getWaitUsers();
                ArrayList<String> onlineCids = new ArrayList<>();
                if (waitUsers.size() > 0 && waitUsers.size() <= 10 && autoAccess.size() > 0) {
                    for (String cid : autoAccess) {
                        if (SessionCache.isSession(cid)) {
                            onlineCids.add(cid);
                        }
                    }
                }
                if (onlineCids.size() > 0) {
                    RedisUtil redisUtil = RedisHelpUtils.getRedisUtil();
                    Object o = redisUtil.get(RedisEunm.AUTOACCESS.keyPrefix);
                    if (o != null) {
                        Integer current = Integer.valueOf(o.toString());
                        int next = current % onlineCids.size();
                        redisUtil.set(RedisEunm.AUTOACCESS.keyPrefix, next);

                    } else {
                        String s = onlineCids.get(0);

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                redisLock.runlock(LOCK_KEY);
            }
        }
    }
}
